package com.p2p.front.web.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.p2p.base.annotation.LoginNeedless;
import com.p2p.base.cache.Cache;
import com.p2p.base.exception.BizException;
import com.p2p.base.model.BaseUser;
import com.p2p.base.model.ValidateCodeSend.BizTypeEnum;
import com.p2p.base.model.ValidateCodeSend.SendEmailTypeEnum;
import com.p2p.base.model.ValidateCodeSend.SendSMSTypeEnum;
import com.p2p.base.util.BasePropertyConfigurer;
import com.p2p.base.util.DateUtil;
import com.p2p.base.util.Encrypter;
import com.p2p.base.util.LoginToken;
import com.p2p.base.util.MD5Util;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.dao.ProtectConstQustionDao;
import com.p2p.front.dal.model.EmailCode;
import com.p2p.front.dal.model.IdCardInfo;
import com.p2p.front.dal.model.IdCardInfo.IdCardStatus;
import com.p2p.front.dal.model.ProtectConstQustion;
import com.p2p.front.dal.model.PwdProtectQuestion;
import com.p2p.front.dal.model.User;
import com.p2p.front.service.BorrowerPhotoService;
import com.p2p.front.service.EmailCodeService;
import com.p2p.front.service.IdCardService;
import com.p2p.front.service.ProtectQuestionService;
import com.p2p.front.service.TenderService;
import com.p2p.front.service.UserInfoAuthService;
import com.p2p.front.service.UserRegisterCheckService;
import com.p2p.front.service.UserRegisterService;
import com.p2p.front.service.UserService;
import com.p2p.front.util.ValidateUtil;
import com.p2p.front.vo.UserCenterResult;
import com.p2p.user.enums.UserAuthName;

/**
 * 用户相关信息维护
 * 
 * @author <a href="mailto:liyang@yiqihao.com">李阳</a>
 * @version 1.0
 */
@Controller
public class UserController extends BaseController {
	private static final String SUCCESS = "success";

	@Resource
	private BorrowerPhotoService borrowerPhotoService;

	@Resource
	private UserRegisterService userRegisterService;

	@Resource
	private UserService userService;
	@Resource
	private Cache defaultCache;

	@Resource
	private UserInfoAuthService userInfoAuthService;

	@Resource
	private ProtectQuestionService protectQuestionService;

	@Resource
	private TenderService tenderService;

	@Resource
	private EmailCodeService emailCodeService;

	@Resource
	private IdCardService idCardService;

	@Resource
	private ProtectConstQustionDao protectConstQuestionDao;
	
	@Resource
	private UserRegisterCheckService userRegisterCheckService;


	@RequestMapping("/modifyPwd")
	public String modifyPwd(Model model) {
		User u = getUser();
		if (u.getPaypwd() != null && !"".equals(u.getPaypwd())) {
			model.addAttribute("payPwd", true);
		}
		initProtectQuestion(model, u.getUid());
		return "userInfo/modifyPwd";
	}

	private void initProtectQuestion(Model model, String uid) {
		PwdProtectQuestion p = protectQuestionService.findByUserId(uid);
		List<ProtectConstQustion> protectConstQuestionList = protectConstQuestionDao
				.listAll();
		model.addAttribute("protectConstQuestionList", protectConstQuestionList);
		if (p != null) {
			model.addAttribute("pwdProtectQuestion", p);
			String answer = "";
			String question = "";
			if (p.getQuestion().equals("custom")) {
				question = p.getQuestionValue();
			} else {
				question = questionIdToString(p.getQuestion(),
						protectConstQuestionList);
			}
			answer = p.getAnswer();
			model.addAttribute("question", question);
			model.addAttribute("answer", answer);
		}
	}

	private String questionIdToString(String question,
			List<ProtectConstQustion> protectConstQuestionList) {
		for (ProtectConstQustion q : protectConstQuestionList) {
			if (q.getId().equals(question)) {
				return q.getName();
			}
		}
		return null;
	}

	@RequestMapping("/saveLoginPwd")
	public void saveLoginPwd(Model model, @RequestParam String password,
			@RequestParam String newPassword, HttpServletResponse response)
			throws Exception {
		JSONObject jsonObj = new JSONObject();
		BaseUser u = getCurrentUser();
		if (MD5Util.sha1(password).equals(u.getPassword())) {
			User user = userService.findById(u.getId());
			user.setPassword(MD5Util.sha1(newPassword));
			userService.update(user);
			u.setPassword(MD5Util.sha1(newPassword));
			// refreshUser(u,response);//刷新BaseUser,无需重登录

			jsonObj.put(SUCCESS, true);
			jsonObj.put("msg", "密码修改成功！");
		} else {
			jsonObj.put(SUCCESS, false);
			jsonObj.put("msg", "原密码错误，请重新输入！");
		}

		returnJsonObject(response, jsonObj);
	}

	/* 设置支付密码 */
	@RequestMapping("/payPassword")
	public String payPassword(Model model) {
		User user = getUser();
		if (user != null && !StringUtils.isEmpty(user.getPaypwd())) {
			return "userInfo/modifyPayPwd";
		} else {
			return "userInfo/setPayPwd";
		}

	}

	/* 保存支付密码 */
	@RequestMapping("/savePayPwd")
	public void savePayPwd(
			Model model,
			@RequestParam(value = "login_pwd", required = false) String login_pwd,
			@RequestParam String pay_pwd,
			@RequestParam(value = "oldPwd", required = false) String oldPwd,
			HttpServletResponse response) {
		JSONObject jsonObj = new JSONObject();
		User u = getUser();
		if (u != null && StringUtils.isEmpty(u.getPaypwd())) {
			// 设置支付密码
			if (u.getPassword().equals(MD5Util.sha1(login_pwd))) {
				u.setPaypwd(MD5Util.sha1(pay_pwd));
				userService.update(u);
				jsonObj.put(SUCCESS, true);
				jsonObj.put("msg", "支付密码设置成功！");
			} else {
				jsonObj.put(SUCCESS, false);
				jsonObj.put("msg", "登录密码错误！");
			}

		} else {
			// 修改支付密码
			if (MD5Util.sha1(oldPwd).equals(u.getPaypwd())) {
				if (MD5Util.sha1(pay_pwd).equals(u.getPassword())) {
					jsonObj.put(SUCCESS, false);
					jsonObj.put("msg", "支付密码不能和登录密码相同！");
				} else {
					u.setPaypwd(MD5Util.sha1(pay_pwd));
					userService.update(u);
					jsonObj.put(SUCCESS, true);
					jsonObj.put("msg", "支付密码修改成功！");
				}
			} else {
				jsonObj.put(SUCCESS, false);
				jsonObj.put("msg", "原支付密码错误！");
			}
		}
		returnJsonObject(response, jsonObj);

	}

	// TODO 貌似没有用到，2个页面也不需要？？？
	@Deprecated
	/* 设置密保问题 */
	@RequestMapping("/pwdProtectQuestion")
	public String pwdProtectQuestion(Model model) {
		BaseUser u = getCurrentUser();
		PwdProtectQuestion p = protectQuestionService.findByUserId(u.getId());
		List<ProtectConstQustion> protectConstQuestionList = protectConstQuestionDao
				.listAll();
		model.addAttribute("protectConstQuestionList", protectConstQuestionList);
		if (p != null) {
			model.addAttribute("pwdProtectQuestion", p);
			model.addAttribute("question", p.getQuestionValue());
			return "userInfo/pwdProtectQuestionUpdate";
		} else {
			return "userInfo/pwdProtectQuestion";
		}

	}

	/* 保存密保问题 */
	@RequestMapping("/savePwdProtectQuestion")
	public void savePwdProtectQuestion(
			Model model,
			@RequestParam(value = "question", required = false) String question,
			@RequestParam(value = "questionValue", required = false) String questionValue,
			@RequestParam(value = "answer", required = false) String answer,
			@RequestParam(value = "oldAnswer", required = false) String oldAnswer,
			HttpServletResponse response) {
		JSONObject jsonObj = new JSONObject();
		BaseUser u = getCurrentUser();
		PwdProtectQuestion protectQuestion = protectQuestionService
				.findByUserId(u.getId());
		// 密保更新
		if (protectQuestion != null) {
			if (protectQuestion.getAnswer().equals(oldAnswer)) {
				protectQuestion.setQuestion(question);
				protectQuestion.setQuestionValue(questionValue);
				protectQuestion.setAnswer(answer);
				protectQuestion.setUserId(u.getId());
				protectQuestionService.update(protectQuestion);
				jsonObj.put(SUCCESS, true);
				jsonObj.put("msg", "密保修改成功！");
			} else {
				jsonObj.put(SUCCESS, false);
				jsonObj.put("msg", "原密保答案错误！");
			}

		} else {// 密保设置
			protectQuestion = new PwdProtectQuestion();
			protectQuestion.setQuestion(question);
			protectQuestion.setQuestionValue(questionValue);
			protectQuestion.setAnswer(answer);
			protectQuestion.setUserId(u.getId());
			protectQuestionService.save(protectQuestion);
			jsonObj.put(SUCCESS, true);
			jsonObj.put("msg", "密保设置成功！");
		}

		returnJsonObject(response, jsonObj);
	}

	/* 忘记登录密码 */
	@RequestMapping("/forgetPwd")
	@LoginNeedless
	public String forgetPwd() {
		return "userInfo/forgetPwd";
	}

	/* 忘记支付密码 */
	@RequestMapping("/forgetPayPwd")
	@LoginNeedless
	public String forgetPayPwd() {
		return "userInfo/forgetPayPwd";
	}

	/* 手机找回登录密码 */
	@RequestMapping("/forgetPwdSMS")
	@LoginNeedless
	public String forgetPwdSMS() {
		return "userInfo/forgetPwdSMS";
	}

	/* 邮箱找回登录密码 */
	@RequestMapping("/forgetPwdEmail")
	@LoginNeedless
	public String forgetPwdEmail() {
		return "userInfo/forgetPwdEmail";
	}

	/* 手机找回支付密码 */
	@RequestMapping("/forgetPayPwdSMS")
	@LoginNeedless
	public String forgetPayPwdSMS() {
		return "userInfo/forgetPayPwdSMS";
	}

	/* 邮箱找回支付密码 */
	@RequestMapping("/forgetPayPwdEmail")
	@LoginNeedless
	public String forgetPwdPayEmail() {
		return "userInfo/forgetPayPwdEmail";
	}

	/* 通过手机重置密码 */
	@RequestMapping("/resetPwd")
	@LoginNeedless
	public String resetPwd(Model model, @RequestParam String mobilephone,
			@RequestParam String code, @RequestParam String newPassword,
			@RequestParam int type, HttpServletResponse response)
			throws Exception {
		// 验证短信验证码
		UserCenterResult userCenterResult = userRegisterService.checkSMSCode(
				mobilephone, code, BizTypeEnum.MobileBindingForGetPwd);

		if (!userCenterResult.isSuccess()) {
			model.addAttribute("errInfo", "验证码不正确");
			return "userInfo/forgetPwd";
		}
		User user = userService.findByPhone(mobilephone);
		if (type == 0) {// 找回登录密码
			user.setPassword(MD5Util.sha1(newPassword));
			userService.update(user);
		} else {// 找回支付密码
			user.setPaypwd(MD5Util.sha1(newPassword));
			userService.update(user);
		}
		return "redirect:/home/index.html";
	}

	@RequestMapping("/resetPwdEmail")
	@LoginNeedless
	public String resetPwdEmail(Model model, @RequestParam String uemail,
			@RequestParam String code, @RequestParam String newPassword,
			@RequestParam int type, HttpServletResponse response)
			throws Exception {
		// 验证短信验证码
		UserCenterResult userCenterResult = userRegisterService.checkSMSCode(
				uemail, code, BizTypeEnum.MailBindingForGetPwd);

		if (!userCenterResult.isSuccess()) {
			model.addAttribute("errInfo", "验证码不正确");
			return "userInfo/forgetPwd";
		}
		User user = userService.findByEmail(uemail);
		if (type == 0) {// 找回登录密码
			user.setPassword(MD5Util.sha1(newPassword));
			userService.update(user);
		} else {// 找回支付密码
			user.setPaypwd(MD5Util.sha1(newPassword));
			userService.update(user);
		}
		return "redirect:/home/index.html";
	}

	/* 通过邮箱重置密码 */
	// @RequestMapping("/resetPwdEmail")
	// @LoginNeedless
	// public String resetPwdEmail(Model model, @RequestParam String email,
	// @RequestParam String newPassword,@RequestParam int type,
	// HttpServletResponse response) throws Exception {
	//
	// User user = userService.findByEmail(email);
	// if(type == 0){//找回登录密码
	// user.setPassword(MD5Util.sha1(newPassword));
	// userService.update(user);
	// }else{//找回支付密码
	// user.setPaypwd(MD5Util.sha1(newPassword));
	// userService.update(user);
	// }
	// return "redirect:/home/index.html";
	// }

	/* 安全认证信息 */
	@RequestMapping(value = "/authInfo", method = RequestMethod.GET)
	public String authInfo(Model model) {
		BaseUser u = (BaseUser) getCurrentUser();
		List<UserAuthName> authNameList = new ArrayList<UserAuthName>();
		authNameList.add(UserAuthName.AUTH_MOBILE);
		authNameList.add(UserAuthName.AUTH_EMAIL);
		authNameList.add(UserAuthName.AUTH_REALNAME);
		Map<Integer, Character> resultMap = userInfoAuthService
				.getAuthByEnumList(u.getId(), authNameList);
		model.addAttribute("realNameStatus",
				resultMap.get(UserAuthName.AUTH_REALNAME.getIndex()).toString());
		model.addAttribute("mobileStatus",
				resultMap.get(UserAuthName.AUTH_MOBILE.getIndex()).toString());
		model.addAttribute("emailStatus",
				resultMap.get(UserAuthName.AUTH_EMAIL.getIndex()).toString());
		IdCardInfo idCardInfo = idCardService.getAuthing(u.getId());
		if (idCardInfo != null) {
			model.addAttribute("authIdCardStatus", idCardInfo.getStatus());
		} else {
			model.addAttribute("authIdCardStatus", -1);
		}
		return "userInfo/authInfo";
	}

	/**
	 * 身份证认证
	 * 
	 * @param userRegisterVo
	 * @return
	 */
	@RequestMapping(value = "/certIdAuthentication", method = RequestMethod.POST)
	public void certIdAuthentication(@RequestParam String realName,
			@RequestParam String cardId, @RequestParam String fileName,
			HttpServletRequest request, Model model,
			HttpServletResponse response) {
		BaseUser u = getCurrentUser();
		JSONObject jsonObj = new JSONObject();

		try {
			String validateResult = ValidateUtil.IDCardValidate(cardId);
			if (!"".equals(validateResult)) {
				jsonObj.put(SUCCESS, false);
				jsonObj.put("msg", validateResult + " *");
				returnJsonObject(response, jsonObj);
				return;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		Map<String, Object> authedCard = userService.findAuthed(cardId);
		if (authedCard == null) {
			IdCardInfo idCard = new IdCardInfo();
			idCard.setRealName(realName);
			idCard.setIdCard(cardId);
			idCard.setUid(u.getId());
			idCard.setStatus(IdCardStatus.TO_AUDIT.getStatus());
			userService.authIdCard(idCard, fileName, u);
			jsonObj.put(SUCCESS, true);
			jsonObj.put("msg", "身份认证信息上传成功，请等待审核通过！");
		} else {
			jsonObj.put(SUCCESS, false);
			jsonObj.put("msg", "该身份证已经认证过一次了。");
		}
		returnJsonObject(response, jsonObj);
	}

	
	/**
	 * 检查用户输入的身份证号和认证的身份证号是否一致
	 * @param idCard
	 */
	@RequestMapping("/checkIdCard")
	public void checkIdCard(@RequestParam String idCard,HttpServletResponse response){
		JSONObject jsonObj = new JSONObject();
		BaseUser baseUser = this.getCurrentUser();
		UserCenterResult result = userRegisterCheckService.checkUidForIdCard(baseUser.getId(), idCard);
		if(result.isSuccess()){
			jsonObj.put(SUCCESS, true);
			this.returnJsonObject(response, jsonObj);
			return;
		}else{
			jsonObj.put(SUCCESS, false);
			jsonObj.put("msg", "校验不一致");
			this.returnJsonObject(response, jsonObj);
			return;
		}
	}
	/* 修改手机号码 */
	@RequestMapping(value = "/modifyMobile", method = RequestMethod.GET)
	public String modifyMobile(Model model) {
		BaseUser u = getCurrentUser();
		//PwdProtectQuestion p = protectQuestionService.findByUserId(u.getId());
		initProtectQuestion(model,u.getId());
		model.addAttribute("mobile", u.getMobilePhone());
		return "userInfo/modifyMobile";
	}

	/* 通过邮箱修改手机号码 */
	@RequestMapping(value = "/modifyMobileEmail", method = RequestMethod.GET)
	public String modifyMobileEmail(Model model) {
		BaseUser u = getCurrentUser();
		model.addAttribute("email", u.getEmail());
		return "userInfo/modifyMobileEmail";
	}

	/* 验证短信验证码 */
	@RequestMapping(value = "/codeValidateBySMS", method = RequestMethod.POST)
	public String modifyMobileBySMS(Model model,
			@RequestParam String umobileId, @RequestParam String code,
			@RequestParam int codeType,
			@RequestParam(value = "paypwd", required = false) String payPwd) {

		/* 验证支付密码 */
		if (!StringUtils.isEmpty(payPwd)) {
			User user = getUser();
			if (!(user.getPaypwd().equals(MD5Util.sha1(payPwd)))) {
				model.addAttribute("errInfo", "支付密码错误！");
				if (codeType == SendSMSTypeEnum.TYPE_MODIFYPHONE.getIndex()) {
					return "userInfo/modifyMobile";
				} else if (codeType == SendSMSTypeEnum.TYPE_MODIFYEMAIL
						.getIndex()) {
					return "userInfo/modifyEmail";
				}

			}
		}

		/* 验证验证码 */
		UserCenterResult userCenterResult = null;
		if (codeType == SendSMSTypeEnum.TYPE_MODIFYPHONE.getIndex()) {
			userCenterResult = userRegisterService.checkSMSCode(umobileId,
					code, BizTypeEnum.MobileBindingForModifyMobile);
			if (userCenterResult.isSuccess())
				return "userInfo/resetMobile";
			else {
				model.addAttribute("errInfo", "验证码不正确");
				return "userInfo/modifyMobile";
			}
		} else if (codeType == SendSMSTypeEnum.TYPE_GETPWD.getIndex()) {
			userCenterResult = userRegisterService.checkSMSCode(umobileId,
					code, BizTypeEnum.MobileBindingForGetPwd);
			if (userCenterResult.isSuccess())
				return "userInfo/resetPwd";
			else {
				model.addAttribute("errInfo", "验证码不正确");
				return "userInfo/forgetPwd";
			}
		} else if (codeType == SendSMSTypeEnum.TYPE_MODIFYEMAIL.getIndex()) {
			userCenterResult = userRegisterService.checkSMSCode(umobileId,
					code, BizTypeEnum.MobileBindingForModifyEmail);
			if (userCenterResult.isSuccess())
				return "userInfo/resetEmail";
			else {
				model.addAttribute("errInfo", "验证码不正确");
				return "userInfo/modifyEmail";
			}
		} else
			return "404";

	}

	/* 修改手机号码只能通过身份证+密保+原手机(邮箱) */
	@RequestMapping(value = "/validateCertIdAndAnswer", method = RequestMethod.POST)
	public void validateCertIdAndAnswer(
			Model model,
			@RequestParam(value = "certId", required = true) String certId,
			@RequestParam(value = "answer", required = true) String answer,
			@RequestParam int type,
			@RequestParam(value = "oldMobile", required = false) String oldMobile,
			@RequestParam(value = "email", required = false) String email,
			@RequestParam String code, HttpServletResponse response) {
		JSONObject jsonObj = new JSONObject();
		
		UserCenterResult userCenterResult = null;
		if (type == SendSMSTypeEnum.TYPE_MODIFYPHONE.getIndex()) {
			if (!"".equals(oldMobile) && null != oldMobile) {
				userCenterResult = userRegisterService.checkSMSCode(oldMobile,
						code, BizTypeEnum.MobileBindingForModifyMobile);
			} else {
				userCenterResult = userRegisterService.checkSMSCode(email,
						code, BizTypeEnum.MailForModifyMobile);
			}
		} else if (type == SendSMSTypeEnum.TYPE_MODIFYEMAIL.getIndex()) {
			if (!"".equals(oldMobile) && null != oldMobile) {
				userCenterResult = userRegisterService.checkSMSCode(oldMobile,
						code, BizTypeEnum.MobileBindingForModifyEmail);
			} else {
				userCenterResult = userRegisterService.checkSMSCode(email,
						code, BizTypeEnum.MailForModifyEmail);
			}
		}else{
			jsonObj.put(SUCCESS, false);
			jsonObj.put("msg", "参数不合法！");
			returnJsonObject(response, jsonObj);
			return;
		}

		if (!userCenterResult.isSuccess()) {
			jsonObj.put(SUCCESS, false);
			jsonObj.put("msg", "验证码不正确！");
			returnJsonObject(response, jsonObj);
			return;
		}

		User user = getUser();
		if (StringUtils.isNotBlank(oldMobile)){
				if(!StringUtils.equals(user.getUmobile(), oldMobile)) {
					jsonObj.put(SUCCESS, false);
					jsonObj.put("msg", "原电话号码不正确！");
					returnJsonObject(response, jsonObj);
					return;
				}
				
		} else {
			if(!StringUtils.equals(user.getUemail(),email)) {
				jsonObj.put(SUCCESS, false);
				jsonObj.put("msg", "邮箱不正确！");
				returnJsonObject(response, jsonObj);
				return;
			}
		}
		
		if(StringUtils.isBlank(user.getIdcard())){
			jsonObj.put(SUCCESS, false);
			jsonObj.put("msg", "请先做身份认证");
			returnJsonObject(response, jsonObj);
			return;
		}
		if(!StringUtils.equals(certId, user.getIdcard())){
			jsonObj.put(SUCCESS, false);
			jsonObj.put("msg", "身份证验证错误！");
			returnJsonObject(response, jsonObj);
			return;
		}
		PwdProtectQuestion p = protectQuestionService.findByUserId(user
				.getUid());
		if (p != null ) {
			/*if (type == SendSMSTypeEnum.TYPE_MODIFYPHONE.getIndex()) {
				if (StringUtils.isEmpty(answer)
						|| !answer.equals(p.getAnswer())) {
					jsonObj.put(SUCCESS, false);
					jsonObj.put("msg", "answer is error！");
					returnJsonObject(response, jsonObj);
					return;
				}
			}*/
			
			if (StringUtils.isNotBlank(answer)
					&& !answer.equals(p.getAnswer())) {
				jsonObj.put(SUCCESS, false);
				jsonObj.put("msg", "密保答案错误！");
				returnJsonObject(response, jsonObj);
				return;
			}
		}
		jsonObj.put(SUCCESS, true);
		jsonObj.put("validata", this.createValidate());
		returnJsonObject(response, jsonObj);
		return;
	}

	/* 保存修改手机号码 */
	@RequestMapping(value = "/saveMobile")
	public void saveMobile(Model model, @RequestParam String mobile,
			@RequestParam String captcha, @RequestParam String validata,HttpServletResponse response)
			throws Exception {
		JSONObject jsonObject= new JSONObject();
		boolean checkValidataResult = checkValidata(validata);
		if(!checkValidataResult){
			jsonObject.put(SUCCESS, false);
			jsonObject.put("errMsg", "请求过期！");
			this.returnJsonObject(response, jsonObject);
			return;
		}
		UserCenterResult userCenterResult = null;
		userCenterResult = userRegisterService.checkSMSCode(mobile, captcha,
				BizTypeEnum.MobileBinding);
		
		if (userCenterResult.isSuccess()) {
			// 更新手机号码
			User user = getUser();
			user.setUmobile(mobile);
			userService.update(user);
			jsonObject.put(SUCCESS, true);
		} else {
			jsonObject.put("errMsg", "验证码错误！");
			jsonObject.put(SUCCESS, false);
		}
		super.returnJsonObject(response, jsonObject);
	
	}

	/* 通过手机号码修改邮箱 */
	@RequestMapping(value = "/modifyEmailBySMS")
	public String modifyEmailBySMS(Model model) {
		BaseUser u = getCurrentUser();
		initProtectQuestion(model,u.getId());
		model.addAttribute("mobile", u.getMobilePhone());
		return "userInfo/modifyEmailBySMS";
	}

	/* 通过原邮箱修改邮箱 */
	@RequestMapping(value = "/modifyEmailByEmail")
	public String modifyEmailByEmail(Model model) {
		BaseUser u = getCurrentUser();
		/*PwdProtectQuestion p = protectQuestionService.findByUserId(u.getId());
		if (p != null) {
			model.addAttribute("pwdProtectQuestion", p);
			model.addAttribute("question", p.getQuestionValue());
		}*/
		initProtectQuestion(model,u.getId());
		model.addAttribute("email", u.getEmail());
		return "userInfo/modifyEmailByEmail";
	}

	/* 保存邮箱 */
	@RequestMapping(value = "/saveEmail")
	public void saveEmail(Model model, @RequestParam String newEmail,
			@RequestParam String captcha, @RequestParam String validata, HttpServletResponse response)
			throws Exception {
		JSONObject jsonObject = new JSONObject();
		UserCenterResult userCenterResult = null;
		boolean checkValidataResult = checkValidata(validata);
		if(!checkValidataResult){
			jsonObject.put(SUCCESS, false);
			jsonObject.put("errMsg", "请求过期！");
			this.returnJsonObject(response, jsonObject);
			return;
		}
		userCenterResult = userRegisterService.checkSMSCode(newEmail, captcha,
				BizTypeEnum.MailBinding);
		
		if (userCenterResult.isSuccess()) {
			// 更新邮箱
			User user = getUser();
			user.setUemail(newEmail);
			userService.update(user);
			jsonObject.put(SUCCESS, true);
		} else {
			jsonObject.put("errMsg", "验证码错误！");
			jsonObject.put(SUCCESS, false);
		}
		this.returnJsonObject(response, jsonObject);
		return;
	}

	private boolean checkValidata(String validata){
		BaseUser baseUser = this.getCurrentUser();
		Object o = defaultCache.getValue("MODIFY_MOBILE_OR_EMAIL_"+baseUser.getId());
		if(o!=null){
			String cacheValidata = (String)o;
			return StringUtils.equals(validata, cacheValidata);
		}
		return false;
	}
	private String createRandomNumber(){
		int number = new Random().nextInt(1000000);
		String str1 = String.format("%06d", number);
		return str1;
	}
	private String createValidate(){
		BaseUser baseUser = this.getCurrentUser();
		
		String randomNumber= createRandomNumber();
		defaultCache.add("MODIFY_MOBILE_OR_EMAIL_"+baseUser.getId(), randomNumber, 120);
		return randomNumber;
	}
	@RequestMapping(value = "/validateEmail/{encryptEmailId}/{encryptCode}/{encryptSendTimeMD5}/{encryptType}/{encryptUserId}", method = RequestMethod.GET)
	@LoginNeedless
	public String validateEmail(
			@PathVariable("encryptEmailId") String encryptEmailId,
			@PathVariable("encryptCode") String encryptCode,
			@PathVariable("encryptType") String encryptType,
			@PathVariable("encryptUserId") String encryptUserId,
			HttpServletResponse response, Model model) throws Exception {
		String sendEmailType = Encrypter.decrypt(encryptType);
		String emailId = Encrypter.decrypt(encryptEmailId);
		String emailAddress = "";
		EmailCode emailCode = emailCodeService.getEmailCodeById(emailId);
		if (emailCode != null) {
			emailAddress = emailCode.getEmail();
		}
		UserCenterResult checkResult = userRegisterService
				.checkRegisterEmailLegal(encryptEmailId, encryptCode,
						sendEmailType, encryptUserId);
		model.addAttribute("email", emailAddress);
		if (!checkResult.isSuccess()) {
			return "register/emailLose";
		} else if (sendEmailType.equals(String
				.valueOf(SendEmailTypeEnum.TYPE_NEWEMAIL.getIndex()))) {
			//User user = getUser();
			String userId = Encrypter.decrypt(encryptUserId);
			User user = userService.findById(userId);
			//userService.updateEmail(user);
			
			String loginDomain = BasePropertyConfigurer.getContextProperty(
					"p2p.loginDomain").toString();
			String userHomeUrl = BasePropertyConfigurer.getContextProperty(
					"p2p.userDomain").toString()
					+ "/authInfo.html";
			String tokenLoginUrl = loginDomain + "/tokenlogin.html?backUrl="
					+ userHomeUrl;
			String token = user.getUmobile() + "," + LoginToken.DEFAULT_SALT
					+ "," + DateUtil.getDateStr(new Date());
			String encrypedToken = Encrypter.encrypt(token);
			tokenLoginUrl += "&token=" + encrypedToken;
			return "redirect:" + tokenLoginUrl;
		} else
			return "404";
	}

	@RequestMapping(value = "/validateEmail/{encryptEmailId}/{encryptCode}/{encryptSendTimeMD5}/{encryptType}", method = RequestMethod.GET)
	@LoginNeedless
	@Deprecated
	public String validateEmailNologin(
			@PathVariable("encryptEmailId") String encryptEmailId,
			@PathVariable("encryptCode") String encryptCode,
			@PathVariable("encryptType") String encryptType,// encryptType
															// 0:找回登录密码邮件验证
															// 1:找回支付密码时邮件验证
															// 2:邮箱认证时邮件验证
			HttpServletResponse response, Model model) throws Exception {
		String sendEmailType = Encrypter.decrypt(encryptType);
		String emailId = Encrypter.decrypt(encryptEmailId);
		String emailAddress = "";
		EmailCode emailCode = emailCodeService.getEmailCodeById(emailId);
		if (emailCode != null) {
			emailAddress = emailCode.getEmail();
		}
		UserCenterResult checkResult = userRegisterService
				.checkRegisterEmailLegal(encryptEmailId, encryptCode,
						sendEmailType, "");
		model.addAttribute("email", emailAddress);
		model.addAttribute("type", sendEmailType);
		if (!checkResult.isSuccess()) {
			return "register/emailLose";
		} else if (sendEmailType.equals(String
				.valueOf(SendEmailTypeEnum.TYPE_GETPWD.getIndex()))) {
			return "userInfo/resetPwd";
		} else if (sendEmailType.equals(String
				.valueOf(SendEmailTypeEnum.TYPE_OLDEMAIL.getIndex()))) {
			return "userInfo/resetEmail";
		} else if (sendEmailType.equals(String
				.valueOf(SendEmailTypeEnum.TYPE_NEWEMAIL.getIndex()))) {
			BaseUser u = getCurrentUser();
			User user = getUser();
			u.setEmail(user.getUemail());
			// refreshUser(u,response);
			return "userInfo/authInfo";
		} else
			return "404";
	}

	protected User getUser() {
		BaseUser u = getCurrentUser();
		User user = userService.findById(u.getId());
		return user;
	}

	@RequestMapping(value = "getExceptionResolve")
	@LoginNeedless
	public void getExceptionResolve(HttpServletResponse response) {
		//Map<String, String> exceptionsMap = new HashMap<String, String>();
		JSONObject jsonObj = new JSONObject();
		/*ResourceBundle bundle = ResourceBundle.getBundle(Const.ERR_MSG);
		Enumeration<String> allName = bundle.getKeys();
		while (allName.hasMoreElements()) {
			// 获取每一个名称
			String name = (String) allName.nextElement();
			// 利用已得到的名称通过资源包获得相应的值
			String value = bundle.getString(name);
			exceptionsMap.put(name, value);
		}*/
		jsonObj.put(SUCCESS, true);
		jsonObj.put("exceptionsMap", BizException.getClobalAllMessage());
		this.returnJsonObject(response, jsonObj);
	}


}
